﻿using System;
using System.Security.Principal;
using System.Web;
using System.Web.Security;
using DomainModel;
using Services.Abstract;

namespace Services.Concrete
{
    public class FormsAuthenticationService : IAuthenticationService
    {
        public void SignIn(User user, bool rememberMe)
        {
            var accountEntry = new AccountEntry(user);

            var authTicket = new FormsAuthenticationTicket(
                1,
                user.Login,
                DateTime.Now,
                DateTime.Now.AddDays(1),
                rememberMe,
                accountEntry.Serialize());

            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

            var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
            {
                Expires = DateTime.Now.Add(FormsAuthentication.Timeout),
            };

            HttpContext.Current.Response.Cookies.Add(authCookie);

            var identity = new CustomIdentity(accountEntry, authTicket.Name);

            HttpContext.Current.User = new GenericPrincipal(identity, identity.GetRoles());
        }

        public void SignOut()
        {
            FormsAuthentication.SignOut();
        }
         
    }
}